import {MyMapObject} from './lodash';
import {getLocal, setLocal} from './local';
import myalert from './alert';
import {link_tab} from './router';


// new Date 转成 Y M D
const formatDate = date => {
  if (!date) { return false }
  if (!(date instanceof Date)) { date = new Date(date) }
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

const formatDateMMDD = date => {
  if (!date) { return false }
  if (!(date instanceof Date)) { date = new Date(date) }
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [month, day].map(formatNumber).join('-')
}

function test(){}







//时间戳转换成日期时间
function formatTimeTwo (unixtime) {
  var dateTime = new Date(parseInt(unixtime))
  var year = dateTime.getFullYear();
  var month = dateTime.getMonth() + 1;
  var day = dateTime.getDate();
  var hour = dateTime.getHours();
  var minute = dateTime.getMinutes();
  var second = dateTime.getSeconds();
  var now = new Date();
  var now_new = Date.parse(now.toDateString());  //typescript转换写法
  var milliseconds = now_new - dateTime;
  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const getWinHeight = () => {
  return wx.getSystemInfoSync().windowHeight
}
const getWinWidth = () => {
  return wx.getSystemInfoSync().windowWidth
}

const rpx2px = (rpx) => {
  return rpx / 750 * getWinWidth()
}
const px2rpx = (px) => {
  return px / getWinWidth() * 750
}
const setTitle = (title) => {
  wx.setNavigationBarTitle({
    title
  })
}
const createParamsUrl = (options) => {
  if (!options) return ""
  var url = ""
  MyMapObject(options, (value, key) => {
    if (value && value != 'undefined') {
      url += `${key}=${value}&`
    }
    if (value && value.constructor == Number && value === 0) {
      url += `${key}=${value}&`
    }
  })
  return url
}

const cc = (str) => {
  console.log(str)
}

const go2Grant = () => {
  var page = getCurrentPages()[0]
  if (page) {
    //授权前界面的options使用cache_options 保存
    setLocal("cache_options", {
      ...page.options,
    })
  }
  // 判断此刻的indexPath 是哪个首页 或者 普通界面
  wx.reLaunch({
    url: `/pages/grant/grant?toPage=${page.route}`
  });
}
const beforeNeedTokenFun = function (strTitle) {
  var self = this
  if (!getLocal('access_token')) {
    return myalert.confirmLogin(strTitle).then(isyes => {
      if (isyes.confirm) {
        // 跳转界面
        go2Grant()
        return Promise.resolve(true)
      } else {
        return Promise.reject(false)
      }
    })

  } else {
    return Promise.resolve(true)
  }
}

const isLogin = function () {
  if (getLocal("access_token")) {
    return true
  } else {
    return false
  }
}
 const clearLogin=function(cb){
  myalert.confirm("确定退出吗").then(isyes=>{
    if(isyes.confirm){
      getApp().globalData.access_token=""
      getApp().globalData.userInfo=null
      setLocal("access_token","")
      setLocal("userInfo","")
      myalert.success("退出成功")
      cb&&cb()
    }
  })
}

const getArea = function (str) {
  let area = {}
  let index11 = 0
  let index1 = str.indexOf("省")
  if (index1 == -1) {
    index11 = str.indexOf("自治区")
    if (index11 != -1) {
      area.Province = str.substring(0, index11 + 3)
    } else {
      area.Province = str.substring(0, 0)
    }
  } else {
    area.Province = str.substring(0, index1 + 1)
  }

  let index2 = str.indexOf("市")
  if (index11 == -1) {
    area.City = str.substring(index11 + 1, index2 + 1)
  } else {
    if (index11 == 0) {
      area.City = str.substring(index1 + 1, index2 + 1)
    } else {
      area.City = str.substring(index11 + 3, index2 + 1)
    }
  }

  let index3 = str.lastIndexOf("区")
  if (index3 == -1) {
    index3 = str.indexOf("县")
    area.Country = str.substring(index2 + 1, index3 + 1)
  } else {
    area.Country = str.substring(index2 + 1, index3 + 1)
  }
  return area;
}
const go2home = () => {
  // replace("/pages/index/index")
  link_tab("/pages/index/index")
}

const go2shopcart = () => {
  // push("/pages/shopcart/shopcart")
  link_tab("/pages/shopcart/shopcart")
}
function isNull (str) {
  if (typeof (str) == "undefined") {
    return true
  }
  if (!str && typeof (str) != "undefined" && str != 0) {
    return true
  }
  if (isNaN(str)) {
    return true
  }
  return false
}
const go2top1 = () => {
  wx.pageScrollTo({
    scrollTop: 0
  })
}
const setShopCartCount = function () {
  var leng = getApp().globalData.shopCarts.length
  if (leng == 0) {
    wx.removeTabBarBadge({//这个方法的意思是，为小程序某一项的tabbar右上角添加文本
      index: 1,   //代表哪个tabbar（从0开始）
    })
    return false
  }

}


function createPostConfigSync (_params) {
  // var productBgImage = await downFile("../images/community-desc-bg.png")
  var productBgImage = "/images/postProductBg.png"
  _params.productBgImage = productBgImage
  console.log("生成  productBgImage", productBgImage)
  var params = createPostConfig(_params)
  return params
}
function createPostConfig (params, options) {
  var {
    productName,
    productPrice,
    productRetailPrice,
    userName,
    codeImage,
    productImage,
    userHeaderImage,
    productSales,
    productStock,
    productBgImage
  } = params
  return {
    ...params,
    width: 750,
    height: 1334,
    backgroundColor: '#F75354',
    pixelRatio: 2,
    debug: false,
    lines: [
      {
        // x: 150,
        // y: 1050,
        startX: 150,
        startY: 1040,
        endX: 150 + 130,
        endY: 1040,
        width: 2,
        color: "#666",
        zIndex: 9,
      }
    ],
    texts: [
      {
        text: "@" + userName,
        x: 280,
        y: 100,
        fontSize: 40,
        color: "#fff",
      },
      {
        text: "分享了一个好东西",
        x: 280,
        y: 160,
        fontSize: 40,
        color: "yellow",
      },
      // product text
      {
        text: productName,
        x: 80,
        y: 910,
        fontSize: 40,
        color: "#222",
        zIndex: 9
      },
      // product retail price 原价
      {
        text: "原价:",
        x: 80,
        y: 1045,
        fontSize: 24,
        color: "#666666",
        zIndex: 9
      },
      {
        text: "￥" + productRetailPrice,
        x: 150,
        y: 1050,
        fontSize: 30,
        color: "#666666",
        // textDecoration: "line-through",
        zIndex: 9,
        width: 240,
      },
      // product price
      {
        text: "社区价:",
        x: 75,
        y: 1115,
        fontSize: 40,
        color: "#FF3333",
        zIndex: 9
      },
      {
        text: "￥" + productPrice,
        x: 220,
        y: 1110,
        fontSize: 40,
        color: "#FF3333",
        zIndex: 9,
      },
      // 销售sales
      {
        text: `已售${productSales}件`,
        x: 80,
        y: 1160,
        fontSize: 24,
        color: "#666666",
        zIndex: 9,
      },
      {
        text: `仅剩${productStock}件`,
        x: 220,
        y: 1160,
        fontSize: 24,
        color: "#666666",
        zIndex: 9,
      },
      // text: 长按识别二维码
      {
        text: "长按识别二维码",
        x: 500,
        y: 1250,
        fontSize: 28,
        color: "#222",
        zIndex: 9,
      },
    ],
    images: [
      // 头像
      {
        width: 130,
        height: 130,
        x: 80,
        y: 50,
        borderRadius: 130,
        url: userHeaderImage,
      },
      // product 背景颜色
      {
        width: 700,
        height: 1050,
        x: 25,
        y: 220,
        url: params.productBgImage,
        // "https://cdn.renqilai.com/2019_09_02/10_24_00_WX20190902-102347.png"
        // url: productBgImage,
        borderRadius: 20,
        background: "#fff",
        zIndex: 8
      },
      // product
      {
        width: 600,
        height: 600,
        x: 80,
        y: 250,
        url: productImage,
        borderRadius: 20,
        background: "#fff",
        zIndex: 8
      },
      // 二维码
      {
        width: 200,
        height: 200,
        x: 500,
        y: 1000,
        url: codeImage,
        borderRadius: 200,
        background: "#fff",
        zIndex: 8
      },
    ]
  }
}
function setAppStore (key, value) {
  getApp().globalData[key] = value
}
function getAppStore (key) {
  return getApp().globalData[key]
}
function clearShopcarts () {
  getApp().globalData.shopCarts = getApp().globalData.shopCarts.filter(item => item.checked != true)
}
function safetoFixed (str, unit = 2) {
  var a = 0;
  try {
    a = parseFloat(str).toFixed(unit)
  } catch (e) {
    a = 0
  }
  return a
}
function downFile (imageUrl) {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url: imageUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath);
        } else {
          reject(res.errMsg);
        }
      },
      fail (err) {
        reject(err);
      },
    });
  })

}



module.exports = {
  safetoFixed,
  getAppStore,
  setAppStore,
  setTitle,
  createPostConfig,
  createPostConfigSync,
  formatDate: formatDate,
  formatTimeTwo: formatTimeTwo,
  getWinHeight,
  getWinWidth,
  rpx2px,
  px2rpx,
  formatDateMMDD,
  createParamsUrl,
  cc,
  go2Grant,
  beforeNeedTokenFun,
  isLogin,
  getArea,
  go2home,
  go2shopcart,
  go2top1,
  setShopCartCount,
  clearShopcarts,
  isNull,
  clearLogin
}
